package cmd

import (
	"fmt"
	"github.com/spf13/cobra"
	"github.com/xiyoufang/cloud-syncer/internal/util"
	"os"
	"regexp"
)

var passwordCmd = &cobra.Command{
	Use:   "password",
	Short: "重置密码",
	Run: func(cmd *cobra.Command, args []string) {
		_, err := os.Stat(configFileName)
		if os.IsNotExist(err) {
			fmt.Printf("配置文件%s不存在\n, 执行`%s config`创建或更新配置文件\n", configFileName, commandLineName)
			return
		}
		content, err := util.ReadFile(configFileName)
		if err != nil {
			fmt.Printf("读取配置文件%s失败\n", configFileName)
			return
		}
		secretKey := util.RandomString(64)
		password := util.RandomString(12) // 随机生成一个密码
		passwordRegex := regexp.MustCompile(`password: .+`)
		secretKeyRegex := regexp.MustCompile(`secretKey: .+`)
		content = passwordRegex.ReplaceAllString(content, fmt.Sprintf("password: %s", util.Sha512Hex([]byte(password), []byte(secretKey))))
		content = secretKeyRegex.ReplaceAllString(content, fmt.Sprintf("secretKey: %s", secretKey))
		if err = util.WriteFile(configFileName, content); err != nil {
			fmt.Printf("更新配置文件%s失败, 错误信息: %v\n", configFileName, err)
			return
		} else {
			fmt.Printf("密码已更新, 新密码为: %v\n", password)
		}
	},
}

func init() {
	rootCmd.AddCommand(passwordCmd)
}
